package com.example.woke1;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.woke.adapter.Mygridadter;
import com.woke.adapter.Mylistadter;
import com.woke.data.Data_child;
import com.woke.diyview.MyGridView;
import com.woke.diyview.MyListView;
import com.woke.httpupload.FileProviderUtils;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.woke.method.UploadImage;
import com.woke.uiviewpay.DateTimePickDialogUtil;
import com.zhongcai.online.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MyfaqiActivity extends FragmentActivity implements OnClickListener, OnItemClickListener, EasyPermissions.PermissionCallbacks {

	private MyGridView mGridView;
	String mCurrentPhotoPath;
	private static final int PHOTO_CAPTURE = 0x11;
	Uri imageUri = null;
	private ArrayList<String> maplist = new ArrayList<String> ();//����Ŀѡ������ѡ���ͼƬ
	private Mygridadter adapter;
	private String stradd = "addmap";
	private MyApp application;
	private MyListView mListView;
	private Mylistadter adapter1;
	private ArrayList<Data_child> childlist = new ArrayList<Data_child> ();
	private ArrayList<String> childmaplist = new ArrayList<String> ();//����Ŀ��ѡ��ͼƬ��ַ
	private String id = "";
	private EditText mEname, mEmoney, mEcontent;
	private String initEndDateTime = "2015年12月23日 17:44"; // ��ʼ������ʱ��
	private TextView mTtime;
	private String timejls;
	private String name;
	private String money;
	private String time;
	private String content;
	private int zhongtype = 1;//1Ϊ��Ʒ�ڳ�2Ϊ��Ȩ
	private String strtime;
	private TextView mTok;
	private View mBar;
	private CheckBox mBox1;
	private boolean checked = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_myfaqi);

		intview ();
		getcurrenttime ();
	}

	private static final int CAMERA = 88;

	@AfterPermissionGranted(CAMERA)
	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.CAMERA};
		if (EasyPermissions.hasPermissions (this, perms)) {
			photo ();
		} else {
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "需要读取本地文件/相机权限",
					CAMERA, perms);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		if (requestCode == CAMERA) {
			photo ();
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		if (requestCode == CAMERA) {
			new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开相机权限")
					.setPositiveButton ("前往", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							intent.setData (Uri.fromParts ("package", getPackageName (), null));
							startActivity (intent);
							dialog.dismiss ();
						}
					})
					.setNegativeButton ("取消", null)
					.create ()
					.show ();
		}
	}

	public void getcurrenttime() {
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日");
		Date curDate = new Date (System.currentTimeMillis ());//��ȡ��ǰʱ��
		strtime = formatter.format (curDate) + "17:44";
		timejls = Intentnet.getTime (strtime);
	}

	private void intview() {
		Intent intent = getIntent ();
		zhongtype = intent.getIntExtra ("zhongtype", 1);
		LayoutInflater inflater = getLayoutInflater ();
		maplist.add (stradd);
		application = (MyApp) getApplication ();
		findViewById (R.id.myfaqi_image_back).setOnClickListener (this);
		mBar = findViewById (R.id.faqi_progress_bar);
		mGridView = (MyGridView) findViewById (R.id.myfaqi_gridview);
		View whengongyi = findViewById (R.id.myfaqi_whengongyi);
		CheckBox mBox = (CheckBox) findViewById (R.id.faqi_checkbox);
		TextView mTtitle = (TextView) findViewById (R.id.myfaqi_text_type);
		mBox1 = (CheckBox) findViewById (R.id.check_myfaqi);
		mBox1.setOnCheckedChangeListener (new OnCheckedChangeListener () {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					checked = true;
//					mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
//					mTok.setClickable(true);
				} else {
					checked = false;
//					mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
//					mTok.setClickable(false);
				}
			}
		});
		if (zhongtype == 3) {
			whengongyi.setVisibility (View.GONE);
			mTtitle.setText ("  公益众筹");
		}
		if (zhongtype == 2) {
			mTtitle.setText ("  股权众筹");
		}
		adapter = new Mygridadter (inflater, maplist, application.screenWidth, MyfaqiActivity.this);
		mListView = (MyListView) findViewById (R.id.myfaqi_listview);
		mGridView.setAdapter (adapter);
		mGridView.setOnItemClickListener (this);
		adapter1 = new Mylistadter (inflater, childlist, application.screenWidth);
		mListView.setAdapter (adapter1);
		findViewById (R.id.faqi_text_addchild).setOnClickListener (this);
		mTok = (TextView) findViewById (R.id.faqi_text_fabu);
		mTok.setOnClickListener (this);
		mTtime = (TextView) findViewById (R.id.myfaqi_text_checktime);
		mTtime.setOnClickListener (this);
		mEname = (EditText) findViewById (R.id.myfaqi_edit_name);
		mEmoney = (EditText) findViewById (R.id.myfaqi_edit_money);
		mEcontent = (EditText) findViewById (R.id.myfaqi_edit_content);
		mBox.setOnCheckedChangeListener (new OnCheckedChangeListener () {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					mTok.setBackgroundDrawable (getResources ().getDrawable (R.drawable.rect_lightred));
					mTok.setClickable (true);
				} else {
					mTok.setBackgroundDrawable (getResources ().getDrawable (R.drawable.rect_lightgray));
					mTok.setClickable (false);
				}
			}
		});
	}


	@Override
	public void onClick(View v) {
		switch (v.getId ()) {
			case R.id.myfaqi_image_back:
				finish ();
				break;

			case R.id.faqi_text_fabu:
				name = "" + mEname.getText ().toString ().trim ();
				money = "" + mEmoney.getText ().toString ().trim ();
				time = "" + mTtime.getText ().toString ().trim ();
				content = "" + mEcontent.getText ().toString ().trim ();
				if (name.equals ("")) {
					Toast.makeText (MyfaqiActivity.this, "请输入项目名称", Toast.LENGTH_SHORT).show ();
				} else if (money.equals ("")) {
					Toast.makeText (MyfaqiActivity.this, "请输入支持金额", Toast.LENGTH_SHORT).show ();
				} else if (time.equals ("")) {
					Toast.makeText (MyfaqiActivity.this, "请输入截止时间", Toast.LENGTH_SHORT).show ();
				} else if (content.equals ("")) {
					Toast.makeText (MyfaqiActivity.this, "请输入项目介绍", Toast.LENGTH_SHORT).show ();
				} else if (maplist.size () < 2) {
					Toast.makeText (MyfaqiActivity.this, "至少选择一张图片", Toast.LENGTH_SHORT).show ();
				} else if (childlist.size () <= 0 && zhongtype != 3) {
					Toast.makeText (MyfaqiActivity.this, "至少选择一种回报方式ʽ", Toast.LENGTH_SHORT).show ();
				} else {
					if (maplist.size () < 4) {
						maplist.remove (maplist.size () - 1);
						senddata (maplist);
					} else {
						senddata (maplist);
					}
				}
				break;

			case R.id.myfaqi_text_checktime:
				DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil (
						MyfaqiActivity.this, strtime);
				dateTimePicKDialog.dateTimePicKDialog (mTtime);
				break;

			case R.id.faqi_text_addchild:
				Intent intent = new Intent (MyfaqiActivity.this, MyfaqichildActivity.class);
				intent.putExtra ("number", childlist.size ());
				startActivityForResult (intent, 666);
				break;

			default:
				break;
		}
	}

	private void senddata(ArrayList<String> datalist) {
		MyTask myTask = new MyTask ();
		myTask.execute ("www.xinlang.com");
	}

	class MyTask extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute ();
//			mFrame.setVisibility(View.VISIBLE);
			mBar.setVisibility (View.VISIBLE);
		}

		@Override
		protected String doInBackground(String... params) {

			//ϵͳ�������������߳�
			UploadImage uload = new UploadImage ();
			if (application.getDatas_load () == null) return String.valueOf (false);
			String upload = uload.uploadda (maplist, name, money, timejls, content, id, zhongtype, application
					.getDatas_load ()
					.getId ());
			return upload;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate (values);
			int in = values[0];
//			mBar.setProgress(in);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute (result);
			mBar.setVisibility (View.GONE);
			Log.e ("result", result);
			if (null != result && result.equals ("true")) {
				Toast.makeText (MyfaqiActivity.this, "发布成功", Toast.LENGTH_SHORT).show ();
				finish ();
			} else {
				Toast.makeText (MyfaqiActivity.this, "上传失败", Toast.LENGTH_SHORT).show ();
			}
//			mFrame.setVisibility(View.GONE);
//			mTextView.setText(result);
		}

	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, final int parent) {

			View view = View
					.inflate (mContext, R.layout.item_popupwindows, null);
			view.startAnimation (AnimationUtils.loadAnimation (mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById (R.id.ll_popup);
			ll_popup.startAnimation (AnimationUtils.loadAnimation (mContext,
					R.anim.push_bottom_in_2));

			setWidth (LayoutParams.FILL_PARENT);
			setHeight (LayoutParams.FILL_PARENT);
			setBackgroundDrawable (new BitmapDrawable ());
			setFocusable (true);
			setOutsideTouchable (true);
			setContentView (view);
			showAtLocation (view, Gravity.BOTTOM, 0, 0);
			update ();

			Button bt1 = (Button) view
					.findViewById (R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById (R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById (R.id.item_popupwindows_cancel);
			bt1.setOnClickListener (new OnClickListener () {
				public void onClick(View v) {
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
						methodRequiresTwoPermission ();
					} else {
						photo ();
					}
					dismiss ();
				}
			});
			bt2.setOnClickListener (new OnClickListener () {
				public void onClick(View v) {
					Intent i = new Intent (
							Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult (i, 1);
					dismiss ();
				}
			});
			bt3.setOnClickListener (new OnClickListener () {
				public void onClick(View v) {
					dismiss ();
				}
			});

		}
	}

	/**
	 * ����û������ʱ���ʾ��ʽ�����ص�ǰʱ��ĸ�ʽ �����yyyyMMdd��ע����ĸy���ܴ�д��
	 *
	 * @param sformat yyyyMMddhhmmss
	 * @return
	 */
	public static String getUserDate(String sformat) {
		Date currentTime = new Date ();
		SimpleDateFormat formatter = new SimpleDateFormat (sformat);
		String dateString = formatter.format (currentTime);
		return dateString;
	}

	private void photo() {

		Intent intent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
		if (intent.resolveActivity (getPackageManager ()) != null) {
			// Ensure that there's a camera activity to handle the intent
			File photo = FileProviderUtils.createImageFile (this);

			if (photo != null) {
				mCurrentPhotoPath = photo.getAbsolutePath ();
//				imageUri = FileProvider.getUriForFile (this, "com.zhongcai.online.fileProvider", photo);
				imageUri = Uri.fromFile (photo);
				intent.putExtra (MediaStore.EXTRA_OUTPUT, imageUri);
				startActivityForResult (intent, PHOTO_CAPTURE);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult (requestCode, resultCode, data);
		String sdStatus = Environment.getExternalStorageState ();
		if (resultCode == RESULT_OK && requestCode == 1) {
			BitmapFactory.Options op = new BitmapFactory.Options ();
			op.inSampleSize = 4;
			ContentResolver resolver = getContentResolver ();
			try {
				Uri originalUri = data.getData (); // ���ͼƬ��uri
				String[] proj = {MediaStore.Images.Media.DATA};
				Cursor cursor = managedQuery (originalUri, proj, null, null, null);
				// ���Ҹ������ ����ǻ���û�ѡ���ͼƬ������ֵ
				int column_index = cursor.getColumnIndexOrThrow (MediaStore.Images.Media.DATA);
				cursor.moveToFirst ();
				// ���������ֵ��ȡͼƬ·��
				String path = cursor.getString (column_index);
				maplist.remove (maplist.size () - 1);
				maplist.add (path);
				if (maplist.size () < 4) {
					maplist.add (stradd);
				}
				adapter.notifyDataSetChanged ();
			} catch (OutOfMemoryError e) {
				Toast.makeText (MyfaqiActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show ();
			}
		}
		if (resultCode == RESULT_OK && requestCode == PHOTO_CAPTURE) {

			maplist.remove (maplist.size () - 1);
			maplist.add (mCurrentPhotoPath);
			if (maplist.size () < 4) {
				maplist.add (stradd);
			}
			adapter.notifyDataSetChanged ();

		}
		if (resultCode == 667 && requestCode == 666) {
			String img = data.getStringExtra ("img");
			String name = data.getStringExtra ("name");
			String money = data.getStringExtra ("money");
			String content = data.getStringExtra ("content");
			id = data.getStringExtra ("id");
			Data_child list = new Data_child (img, name, money);
			childlist.add (list);
			adapter1.notifyDataSetChanged ();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (maplist.size () <= 5) {
			if (maplist.get (arg2).equals (stradd)) {
				new PopupWindows (MyfaqiActivity.this, 1);
			}
		}
	}
}
